use ftp::{FtpStream, FtpError};
use std::io::Write;
use std::time::Duration;
use std::fs::OpenOptions;
use std::io::Error;

const PORT: &str = "21";

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let argc = args.len();

    let mut host_addr = String::from("127.0.0.1");
    if argc > 1 {
        let addr = String::from(args[1].clone()) + ":" + PORT;
        host_addr = addr;
    } else {
        host_addr += ":";
        host_addr += PORT;
    }
    println!("Hello, {}!", host_addr);

    let mut ftp = FtpStream::connect(host_addr).unwrap();
    let _ = ftp.get_ref().set_read_timeout(Some(Duration::from_secs(10))).unwrap();

    let _ = ftp.login("anonymous", "").unwrap();

    let _ = ftp.cwd("/").unwrap();

    let _ = ftp.transfer_type(ftp::types::FileType::Binary);

    let resp = ftp.list(None).unwrap();

    for item in resp {
        println!("{:?}", item);
    }

    let size = ftp.size("84402.ISO").unwrap();
    match size {
        Some(_sz) => {println!("{}", _sz)},
        None => {}
    }

    // let cursor = ftp.simple_retr("84402.ISO").unwrap();

    // let mut bin = fs::File::create("84402.ISO").unwrap();
    // let wr = bin.write(&cursor.into_inner()).unwrap();
    // println!("{}", wr);

    ftp.retr("84402.ISO", |stream| {
        let mut buf = Vec::new();
        // stream.read_to_end(&mut buf).map_err(|e| FtpError::ConnectionError(e))
        let ret = stream.read(&mut buf);
        match ret {
            Ok(_sz) => {
                println!("{}", buf.len());
                if _sz > 0 {
                    let mut iso = OpenOptions::new()
                                                .write(true)
                                                .create(true)
                                                .truncate(true)
                                                .open("84402.ISO").unwrap();
                    iso.write(&buf).map_err(|e| FtpError::ConnectionError(e))
                } else {
                    Ok(0)
                }
            },
            Err(_e) => {
                Err(FtpError::ConnectionError(_e))
            }
        }
    }).unwrap();

    let _ = ftp.quit().unwrap();
}
